package com.bmt.pos.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;

import com.bmt.common.LoginUser;
import com.bmt.core.BaseService;
import com.bmt.core.ISaveable;
import com.bmt.core.PageListInfo;
import com.bmt.exception.ServiceException;
import com.bmt.pos.bean.User;
import com.bmt.pos.dao.UserDao;

@Service("userService")
public class UserService extends BaseService {

	@Autowired
	private UserDao userDao;

	@Autowired
	private UserModuleService userModuleService;

	public void addUser(User user) throws ServiceException {
		try {
			userDao.addUser(user);
		} catch (Exception e) {
			throw new ServiceException("添加失败", e);
		}

	}

	public User getUserById(Integer id) throws ServiceException {
		try {
			return userDao.getUserByColunm("id", id);
		} catch (Exception e) {
			throw new ServiceException("获取失败", e);
		}
	}

	public List<User> getUsers() throws ServiceException {
		try {
			return userDao.getUsers();
		} catch (Exception e) {
			throw new ServiceException("获取失败", e);
		}
	}

	public LoginUser login(String userName, String pwd) throws ServiceException {
		try {
			User user = userDao.getUserByColunm("userName", userName);
			LoginUser loginUser = new LoginUser();
			loginUser.setUser(user);
			loginUser.getUserList().add(user);
			userModuleService.processUserModuleList(loginUser);
			return loginUser;
		} catch (Exception e) {
			if (e instanceof EmptyResultDataAccessException) {
				return null;
			}
			throw new ServiceException("获取失败", e);
		}
	}

	public PageListInfo<ISaveable> getPageInfo(int pageNum) throws ServiceException {
		try {
			return userDao.getPageListInfo(pageNum);
		} catch (Exception e) {
			throw new ServiceException("获取失败", e);
		}
	}

}
